package com.woniu.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.core.exception.account.AccountException;
import com.woniu.core.exception.account.AccountExceptionCode;
import com.woniu.core.util.JwtUtil;
import com.woniu.core.util.PageInfo;
import com.woniu.core.util.Result;
import com.woniu.order.client.AccountServerClient;
import com.woniu.order.client.dto.GetUserInfoByIdDTO;
import com.woniu.order.dao.TCourseOrderMapper;
import com.woniu.order.dto.AdminOrderSearchDto;
import com.woniu.order.dto.TCourseOrderDto;
import com.woniu.order.form.AdminOrderSearchForm;
import com.woniu.order.form.UserRefundForm;
import com.woniu.order.model.TCourseOrder;
import com.woniu.order.service.TCourseOrderService;
import com.woniu.order.util.AlipayUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 吴彦祖
 * @since 2024年04月02日
 */
@Service
public class TCourseOrderServiceImpl extends ServiceImpl<TCourseOrderMapper, TCourseOrder> implements TCourseOrderService {

    @Resource
    private AccountServerClient accountServerClient;
    @Resource
    private TCourseOrderMapper tCourseOrderMapper;
    @Resource
    private AlipayUtil alipayUtil;
    @Override
    public List<TCourseOrderDto> search(Integer userId) throws Exception {
        if (userId == null) throw new AccountException(AccountExceptionCode.USER_NOT_LOGIN);
        Result<GetUserInfoByIdDTO> info = accountServerClient.getUserInfoById(userId);
        if (info.getCode() != 200)throw new AccountException(AccountExceptionCode.NOT_FIND_THIS_USER);
        QueryWrapper<TCourseOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",info.getData().getUserId());
        List<TCourseOrder> list = tCourseOrderMapper.selectList(wrapper);
        ArrayList<TCourseOrderDto> data = new ArrayList<TCourseOrderDto>();
        BigDecimal allOrderMoney=BigDecimal.ZERO;
        for (TCourseOrder tCourseOrder : list) {
            TCourseOrderDto dto = BeanUtil.toBean(tCourseOrder, TCourseOrderDto.class);
            //算出所有购买课程的总金额
            allOrderMoney = allOrderMoney.add(tCourseOrder.getOrderMoney());
            data.add(dto);
        }
        // 设置所有订单的总金额
        for (TCourseOrderDto dto : data) {
            dto.setAllOrderMoney(allOrderMoney);
        }
        return data;
    }

    @Override
    public PageInfo<AdminOrderSearchDto> adminList(AdminOrderSearchForm form) throws Exception {
        Page<TCourseOrder> page = new Page<>(form.getPageNum()==null?1:form.getPageNum(),form.getPageSize()==null?10:form.getPageSize());
        QueryWrapper<TCourseOrder> wrapper = new QueryWrapper<>();
        if(ObjectUtil.isAllNotEmpty(form.getGymNum())){
            wrapper.eq("gym_num",form.getGymNum());
        }
        if(ObjectUtil.isAllNotEmpty(form.getOrderNum())){
            wrapper.eq("order_num",form.getOrderNum());
        }
        if(ObjectUtil.isAllNotEmpty(form.getOrderState())){
            wrapper.eq("order_state",form.getOrderState());
        }
        tCourseOrderMapper.selectPage(page,wrapper);
        List<TCourseOrder> list = page.getRecords();
        ArrayList<AdminOrderSearchDto> data = new ArrayList<>();
        for (TCourseOrder tCourseOrder : list) {
            AdminOrderSearchDto dto = BeanUtil.toBean(tCourseOrder, AdminOrderSearchDto.class);
            data.add(dto);
        }
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setList(data);
        pageInfo.setPages(page.getPages());
        pageInfo.setCurrent((form.getPageNum()==null?1L:form.getPageNum()));
        pageInfo.setSize(form.getPageSize()==null?10L:form.getPageSize());
        int intValue = data.size(); // 定义一个int类型的整数
        long longValue = intValue; // 将int类型的整数赋值给long类型的变量
        pageInfo.setTotal(longValue);
        return pageInfo;
    }

    @Override
    public String refund(UserRefundForm form) throws Exception {
        //订单是不是你的，可不可以退
        List<TCourseOrder> list = tCourseOrderMapper.selectList(new QueryWrapper<TCourseOrder>().eq("user_id",form.getUserId()));
        boolean b=false;
        for (TCourseOrder orderInfo : list) {
            if(orderInfo.getOrderNum().equals(form.getOrderNum())){
                b=true;
                break;
            }
        }
        if(!b){
            throw new Exception("订单不存在");
        }
        TCourseOrder orderInfo = tCourseOrderMapper.selectOne(new QueryWrapper<TCourseOrder>().eq("order_num",form.getOrderNum()));
        if(orderInfo.getOrderState()!=1){
            throw new Exception("无法退款");
        }
        if(orderInfo.getOrderState()==3){
            throw new Exception("订单已完成，不能退款");
        }
        String result = alipayUtil.refund(form);
        String code= JSONUtil.parseObj(JSONUtil.parseObj(result).get("alipay_trade_refund_response").toString()).get("code").toString();
        String fundChange=JSONUtil.parseObj(JSONUtil.parseObj(result).get("alipay_trade_refund_response").toString()).get("fund_change").toString();
        if(code.equals("10000")&&fundChange.equals("Y")){
            orderInfo.setOrderState(2);
            //修改以后一定要更新数据库！！！！！！！
            tCourseOrderMapper.updateById(orderInfo);
            return "SUCCESS";
        }else {
            throw new Exception("退款失败");
        }
    }
}
